<template>
    <el-drawer 
        v-if="nowData"
        :title="nowData.title"
        :visible="editIndex !== -1"
        :direction="direction"
        :before-close="handleClose">
            <div class="contain-right">
                <el-form ref="form" label-width="120px">
                    <el-form-item v-for="(v, i) in schemaArr"  :key="i" :label="nowData.schema[v].title">
                        <el-input v-model="data[v]"></el-input>
                    </el-form-item>
                </el-form>
                <div class="button-wrap">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="submitData">确定</el-button>
                </div>
            </div>
    </el-drawer>
</template>

<script>
export default {
  name: 'RightDrawer',
  props: {
      editIndex: Number,
      toggleShowDrawer: Function
  },
  computed: {
    nowData () {
      let obj = this.$store.state.config.data.pageData[this.editIndex];
      return obj
    },
    dataProps () {
        let obj = this.$store.state.config.data.pageData[this.editIndex];
        return obj && obj.props;
    },
    schemaArr () {
        let obj = this.$store.state.config.data.pageData[this.editIndex];
        return obj && Object.keys(obj.schema) || []
    }
  },
  data () {
    return {
        direction:"rtl",
        data: {

        }
    }
  },
  watch:{
    editIndex (newV, oldV) {
        console.log(this.dataProps)
        console.log(this.schemaArr)
         console.log(this.nowData)
        let obj = {};
        this.schemaArr.forEach(v => {
            obj[v] = this.dataProps[v] || "";
        })
        this.data = obj;
    }
  },
  methods: {
    submitData(){
        let pageData= this.$utils.deepCopy(this.$store.state.config.data.pageData);
        pageData[this.editIndex].props = this.data;
          this.$http.post("/pageData/update", {
          id: pageData[this.editIndex].id,
          props: JSON.stringify(this.data)
      }).then((res) => {
          if (res.success) {
            this.$message({
              message: "更新成功",
              type: "success",
            });
            this.$store.commit('CONFIG_SET', {pageData: pageData});
            this.$message("修改成功");
          }
        })
        .catch((e) => {
          console.log(e);
        });
        
    },
    handleClose () {
        this.toggleShowDrawer(-1)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="stylus" scoped>
    .contain-right
        padding 0 40px
        height 100%
        display flex
        flex-direction column
        justify-content space-between
        .button-wrap
            display flex
            justify-content flex-end
            padding-bottom 20px
</style>

